// 性能监控组件
// 优化标签页和编辑器的性能，实现懒加载、内存回收等机制

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Activity, 
  MemoryStick, 
  Clock, 
  Zap, 
  AlertTriangle,
  CheckCircle,
  XCircle,
  Settings
} from 'lucide-react';
import { useTabStore } from '../stores/tabStore';
import { getEditorInstanceManager } from '../services/editorInstanceManager';
import { cn } from '../utils/cn';

// 性能指标接口
interface PerformanceMetrics {
  memoryUsage: {
    total: number;        // 总内存使用量 (MB)
    editors: number;      // 编辑器内存使用量 (MB)
    tabs: number;         // 标签页内存使用量 (MB)
    system: number;       // 系统内存使用量 (MB)
  };
  performance: {
    renderTime: number;   // 平均渲染时间 (ms)
    responseTime: number; // 平均响应时间 (ms)
    fps: number;          // 帧率
  };
  resources: {
    tabCount: number;     // 标签页数量
    editorInstances: number; // 编辑器实例数量
    modelCount: number;   // 模型数量
    activeConnections: number; // 活动连接数
  };
  health: {
    status: 'good' | 'warning' | 'critical';
    issues: string[];
    recommendations: string[];
  };
}

// 性能阈值配置
const PERFORMANCE_THRESHOLDS = {
  memory: {
    warning: 100,   // 100MB
    critical: 200,  // 200MB
  },
  renderTime: {
    warning: 16,    // 16ms (60fps)
    critical: 33,   // 33ms (30fps)
  },
  responseTime: {
    warning: 100,   // 100ms
    critical: 500,  // 500ms
  },
  tabs: {
    warning: 15,    // 15个标签页
    critical: 20,   // 20个标签页
  },
};

// 性能监控组件属性
interface PerformanceMonitorProps {
  className?: string;
  updateInterval?: number;
  showDetails?: boolean;
  onPerformanceIssue?: (metrics: PerformanceMetrics) => void;
}

// 性能监控组件
export const PerformanceMonitor: React.FC<PerformanceMonitorProps> = ({
  className,
  updateInterval = 5000, // 5秒更新一次
  showDetails = false,
  onPerformanceIssue,
}) => {
  const [metrics, setMetrics] = useState<PerformanceMetrics | null>(null);
  const [isCollecting, setIsCollecting] = useState(false);
  const [showDetailedView, setShowDetailedView] = useState(showDetails);

  const { tabs, tabOrder } = useTabStore();

  // 收集性能指标
  const collectMetrics = useCallback(async (): Promise<PerformanceMetrics> => {
    const editorManager = getEditorInstanceManager();
    const editorInstances = editorManager.getAllInstances();
    
    // 内存使用量计算
    const editorsMemory = editorManager.getTotalMemoryUsage();
    const tabsMemory = Array.from(tabs.values()).reduce((total, tab) => {
      return total + (new Blob([tab.content]).size / (1024 * 1024));
    }, 0);
    
    // 估算系统内存使用量
    const systemMemory = (performance as any).memory ? 
      (performance as any).memory.usedJSHeapSize / (1024 * 1024) : 0;
    
    const totalMemory = editorsMemory + tabsMemory + systemMemory;

    // 性能指标计算
    const renderTime = measureRenderTime();
    const responseTime = measureResponseTime();
    const fps = measureFPS();

    // 资源统计
    const resources = {
      tabCount: tabs.size,
      editorInstances: editorInstances.length,
      modelCount: editorInstances.length, // 假设每个实例一个模型
      activeConnections: 0, // 这里可以添加实际的连接数统计
    };

    // 健康状态评估
    const health = assessHealth({
      memoryUsage: { total: totalMemory, editors: editorsMemory, tabs: tabsMemory, system: systemMemory },
      performance: { renderTime, responseTime, fps },
      resources,
    });

    return {
      memoryUsage: {
        total: totalMemory,
        editors: editorsMemory,
        tabs: tabsMemory,
        system: systemMemory,
      },
      performance: {
        renderTime,
        responseTime,
        fps,
      },
      resources,
      health,
    };
  }, [tabs]);

  // 测量渲染时间
  const measureRenderTime = (): number => {
    // 这里应该实现实际的渲染时间测量
    // 暂时返回模拟值
    return Math.random() * 20 + 5;
  };

  // 测量响应时间
  const measureResponseTime = (): number => {
    // 这里应该实现实际的响应时间测量
    // 暂时返回模拟值
    return Math.random() * 50 + 10;
  };

  // 测量FPS
  const measureFPS = (): number => {
    // 这里应该实现实际的FPS测量
    // 暂时返回模拟值
    return Math.random() * 10 + 55;
  };

  // 评估健康状态
  const assessHealth = (data: Omit<PerformanceMetrics, 'health'>): PerformanceMetrics['health'] => {
    const issues: string[] = [];
    const recommendations: string[] = [];
    let status: 'good' | 'warning' | 'critical' = 'good';

    // 内存检查
    if (data.memoryUsage.total > PERFORMANCE_THRESHOLDS.memory.critical) {
      status = 'critical';
      issues.push('内存使用量过高');
      recommendations.push('关闭一些标签页或重启应用');
    } else if (data.memoryUsage.total > PERFORMANCE_THRESHOLDS.memory.warning) {
      if (status === 'good') status = 'warning';
      issues.push('内存使用量较高');
      recommendations.push('考虑关闭不需要的标签页');
    }

    // 渲染时间检查
    if (data.performance.renderTime > PERFORMANCE_THRESHOLDS.renderTime.critical) {
      status = 'critical';
      issues.push('渲染性能严重下降');
      recommendations.push('减少同时打开的文件数量');
    } else if (data.performance.renderTime > PERFORMANCE_THRESHOLDS.renderTime.warning) {
      if (status !== 'critical') status = 'warning';
      issues.push('渲染性能下降');
      recommendations.push('优化编辑器设置');
    }

    // 标签页数量检查
    if (data.resources.tabCount > PERFORMANCE_THRESHOLDS.tabs.critical) {
      status = 'critical';
      issues.push('标签页数量过多');
      recommendations.push('关闭不需要的标签页');
    } else if (data.resources.tabCount > PERFORMANCE_THRESHOLDS.tabs.warning) {
      if (status !== 'critical') status = 'warning';
      issues.push('标签页数量较多');
      recommendations.push('考虑使用标签页分组');
    }

    return { status, issues, recommendations };
  };

  // 定期更新指标
  useEffect(() => {
    let intervalId: NodeJS.Timeout;

    const updateMetrics = async () => {
      setIsCollecting(true);
      try {
        const newMetrics = await collectMetrics();
        setMetrics(newMetrics);

        // 如果有性能问题，触发回调
        if (newMetrics.health.status !== 'good') {
          onPerformanceIssue?.(newMetrics);
        }
      } catch (error) {
        console.error('Failed to collect performance metrics:', error);
      } finally {
        setIsCollecting(false);
      }
    };

    // 立即执行一次
    updateMetrics();

    // 设置定期更新
    intervalId = setInterval(updateMetrics, updateInterval);

    return () => {
      clearInterval(intervalId);
    };
  }, [collectMetrics, updateInterval, onPerformanceIssue]);

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'good':
        return <CheckCircle size={16} className="text-green-500" />;
      case 'warning':
        return <AlertTriangle size={16} className="text-yellow-500" />;
      case 'critical':
        return <XCircle size={16} className="text-red-500" />;
      default:
        return <Activity size={16} className="text-gray-500" />;
    }
  };

  // 格式化内存大小
  const formatMemory = (mb: number): string => {
    if (mb < 1) {
      return `${(mb * 1024).toFixed(1)} KB`;
    }
    return `${mb.toFixed(1)} MB`;
  };

  if (!metrics) {
    return (
      <div className={cn('flex items-center space-x-2 text-sm text-gray-500', className)}>
        <Activity size={16} className="animate-pulse" />
        <span>收集性能数据中...</span>
      </div>
    );
  }

  return (
    <div className={cn('bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg', className)}>
      {/* 简化视图 */}
      <div className="flex items-center justify-between p-3">
        <div className="flex items-center space-x-3">
          {getStatusIcon(metrics.health.status)}
          <div className="flex items-center space-x-4 text-sm">
            <div className="flex items-center space-x-1">
              <MemoryStick size={14} />
              <span>{formatMemory(metrics.memoryUsage.total)}</span>
            </div>
            <div className="flex items-center space-x-1">
              <Clock size={14} />
              <span>{metrics.performance.renderTime.toFixed(1)}ms</span>
            </div>
            <div className="flex items-center space-x-1">
              <Zap size={14} />
              <span>{metrics.performance.fps.toFixed(0)} FPS</span>
            </div>
          </div>
        </div>
        
        <button
          className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700"
          onClick={() => setShowDetailedView(!showDetailedView)}
          title="切换详细视图"
        >
          <Settings size={16} />
        </button>
      </div>

      {/* 详细视图 */}
      {showDetailedView && (
        <div className="border-t border-gray-200 dark:border-gray-700 p-4 space-y-4">
          {/* 内存使用情况 */}
          <div>
            <h4 className="text-sm font-semibold mb-2 flex items-center">
              <MemoryStick size={16} className="mr-2" />
              内存使用情况
            </h4>
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-600 dark:text-gray-400">编辑器:</span>
                <span className="ml-2 font-mono">{formatMemory(metrics.memoryUsage.editors)}</span>
              </div>
              <div>
                <span className="text-gray-600 dark:text-gray-400">标签页:</span>
                <span className="ml-2 font-mono">{formatMemory(metrics.memoryUsage.tabs)}</span>
              </div>
              <div>
                <span className="text-gray-600 dark:text-gray-400">系统:</span>
                <span className="ml-2 font-mono">{formatMemory(metrics.memoryUsage.system)}</span>
              </div>
              <div>
                <span className="text-gray-600 dark:text-gray-400">总计:</span>
                <span className="ml-2 font-mono font-semibold">{formatMemory(metrics.memoryUsage.total)}</span>
              </div>
            </div>
          </div>

          {/* 性能指标 */}
          <div>
            <h4 className="text-sm font-semibold mb-2 flex items-center">
              <Activity size={16} className="mr-2" />
              性能指标
            </h4>
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div>
                <span className="text-gray-600 dark:text-gray-400">渲染时间:</span>
                <span className="ml-2 font-mono">{metrics.performance.renderTime.toFixed(1)}ms</span>
              </div>
              <div>
                <span className="text-gray-600 dark:text-gray-400">响应时间:</span>
                <span className="ml-2 font-mono">{metrics.performance.responseTime.toFixed(1)}ms</span>
              </div>
              <div>
                <span className="text-gray-600 dark:text-gray-400">帧率:</span>
                <span className="ml-2 font-mono">{metrics.performance.fps.toFixed(0)} FPS</span>
              </div>
            </div>
          </div>

          {/* 资源统计 */}
          <div>
            <h4 className="text-sm font-semibold mb-2">资源统计</h4>
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-600 dark:text-gray-400">标签页:</span>
                <span className="ml-2">{metrics.resources.tabCount}</span>
              </div>
              <div>
                <span className="text-gray-600 dark:text-gray-400">编辑器实例:</span>
                <span className="ml-2">{metrics.resources.editorInstances}</span>
              </div>
            </div>
          </div>

          {/* 健康状态 */}
          {metrics.health.issues.length > 0 && (
            <div>
              <h4 className="text-sm font-semibold mb-2 flex items-center">
                {getStatusIcon(metrics.health.status)}
                <span className="ml-2">健康状态</span>
              </h4>
              
              {metrics.health.issues.length > 0 && (
                <div className="mb-2">
                  <span className="text-xs font-medium text-gray-600 dark:text-gray-400">问题:</span>
                  <ul className="text-sm mt-1 space-y-1">
                    {metrics.health.issues.map((issue, index) => (
                      <li key={index} className="text-red-600 dark:text-red-400">
                        • {issue}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
              
              {metrics.health.recommendations.length > 0 && (
                <div>
                  <span className="text-xs font-medium text-gray-600 dark:text-gray-400">建议:</span>
                  <ul className="text-sm mt-1 space-y-1">
                    {metrics.health.recommendations.map((rec, index) => (
                      <li key={index} className="text-blue-600 dark:text-blue-400">
                        • {rec}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* 收集状态指示器 */}
      {isCollecting && (
        <div className="absolute top-2 right-2">
          <Activity size={12} className="animate-pulse text-blue-500" />
        </div>
      )}
    </div>
  );
};
